<template>
  <Dialog width="60%" :title="dialogTitle" v-model="dialogVisible">
    <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        v-loading="formLoading"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="患者编号" prop="patId">
            <el-input v-model="formData.patId" placeholder="请输入患者编号" clearable @input="searchBookInfo"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="患者姓名" prop="patName">
            <el-input v-model="formData.patName" placeholder="请输入患者姓名" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="患者性别" prop="patGender">
            <el-radio-group v-model="formData.patGender">
              <el-radio
                  v-for="dict in getIntDictOptions(DICT_TYPE.SYSTEM_USER_SEX)"
                  :key="dict.value"
                  :value="dict.value"
              >
                {{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="预约编号" prop="bookId">
            <el-input v-model="formData.bookId" placeholder="请输入预约编号" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="预约日期" prop="bookDate">
            <el-date-picker
                v-model="formData.bookDate"
                type="date"
                value-format="x"
                placeholder="选择预约日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="预约时间" prop="bookTimeslot">
            <el-select v-model="formData.bookTimeslot" placeholder="请选择预约时间段">
              <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.ECG_BOOK_TIMESLOT)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="检查类型" prop="bookCheckType">
            <el-select v-model="formData.bookCheckType" placeholder="请选择检查类型">
              <el-option
                  v-for="dict in checkTypeStore.getCheckTypeOptions()"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="患者生日" prop="patBirthday">
            <el-date-picker
                v-model="formData.patBirthday"
                type="date"
                value-format="x"
                placeholder="选择患者生日"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="患者手机" prop="patMobile">
            <el-input v-model="formData.patMobile" placeholder="请输入患者手机" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="患者电话" prop="patPhone">
            <el-input v-model="formData.patPhone" placeholder="请输入患者电话" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="身份证号" prop="patIdentityId">
            <el-input v-model="formData.patIdentityId" placeholder="请输入身份证号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="患者地址" prop="patAddr">
            <el-input v-model="formData.patAddr" placeholder="请输入患者地址" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="科室代码" prop="patDeptCode">
            <el-input v-model="formData.patDeptCode" placeholder="请输入科室代码" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="科室名称" prop="patDeptDesc">
            <el-input v-model="formData.patDeptDesc" placeholder="请输入科室名称" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="病区代码" prop="patWardCode">
            <el-input v-model="formData.patWardCode" placeholder="请输入病区代码" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="病区名称" prop="patWardDesc">
            <el-input v-model="formData.patWardDesc" placeholder="请输入病区名称" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="床号" prop="patBedNo">
            <el-input v-model="formData.patBedNo" placeholder="请输入床号" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="付款标记" prop="paid">
        <el-checkbox v-model="formData.paid" :true-label=1 :false-label=0>
          已付款
        </el-checkbox>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import {DICT_TYPE, getIntDictOptions} from '@/utils/dict'
import { AppointmentApi, AppointmentVO } from '@/api/ecg/appointment'
import {useCheckTypeStore} from "@/store/modules/checkType";

/** 预约 表单 */
defineOptions({ name: 'AppointmentForm' })

const checkTypeStore = useCheckTypeStore();

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  patId: undefined,
  patName: undefined,
  patGender: 1, // 1 男 2 女
  patBirthday: undefined,
  patMobile: undefined,
  patPhone: undefined,
  patIdentityId: undefined,
  patAddr: undefined,
  patDeptCode: undefined,
  patDeptDesc: undefined,
  patWardCode: undefined,
  patWardDesc: undefined,
  patBedNo: undefined,
  bookId: undefined,
  bookTime: undefined,
  bookDate: new Date().getTime(),
  bookTimeslot: 9000930,
  bookCheckType: 100, //常规检查
  paid: 0,
})
const formRules = reactive({
  patId: [{ required: true, message: '患者编号不能为空', trigger: 'blur' }],
  patName: [{ required: true, message: '患者姓名不能为空', trigger: 'blur' }],
  patGender: [{ required: true, message: '患者性别不能为空', trigger: 'blur' }],
  // bookId: [{ required: true, message: '预约编号不能为空', trigger: 'blur' }],
  bookDate: [{ required: true, message: '预约日期不能为空', trigger: 'blur' }],
  bookTimeslot: [{ required: true, message: '预约检查时间段不能为空', trigger: 'blur' }],
  bookCheckType: [{ required: true, message: '预约检查类型不能为空', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await AppointmentApi.getAppointment(id)
    } finally {
      formLoading.value = false
    }
  }
}
const openByQueue = async (type: string, patId: string, checkType: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (patId) {
    formLoading.value = true
    try {
      formData.value = await AppointmentApi.getCurAppointmentByPatIdAndCheckType( patId, checkType )
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open, openByQueue }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['event_appointment_success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as AppointmentVO
    if (formType.value === 'create') {
      await AppointmentApi.createAppointment(data)
      // 发送操作成功的事件
      emit('event_appointment_success')
      message.success(t('common.createSuccess'))
    } else if (formType.value === 'update') {
      await AppointmentApi.updateAppointment(data)
      // 发送操作成功的事件
      emit('event_appointment_success')
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    patId: undefined,
    patName: undefined,
    patGender: 1, // 1 男 2 女
    patBirthday: undefined,
    patMobile: undefined,
    patPhone: undefined,
    patIdentityId: undefined,
    patAddr: undefined,
    patDeptCode: undefined,
    patDeptDesc: undefined,
    patWardCode: undefined,
    patWardDesc: undefined,
    patBedNo: undefined,
    bookId: undefined,
    bookTime: undefined,
    bookDate: new Date().getTime(),
    bookTimeslot: 9000930,
    bookCheckType: checkTypeStore.getCheckTypeName(100),
    paid: 0,
  }
  formRef.value?.resetFields()
}

const searchBookInfo = async () => {
  const tmpPatId = formData.value.patId
  if (null === tmpPatId || "" === tmpPatId)
    return

  const data = await AppointmentApi.queryAppointmentFromHis( tmpPatId ) // 对应数据库中 pat_id
  console.info( data )
  if (null !== data) {
    formData.value = data
    return
  }

  ElNotification({
    title: '温馨提示',
    message: "没有开单信息",
    type: 'warning'
  })
}

</script>
